package com.server;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Helper.ReservationHelper;
import com.database.CustomerDB;

public class CustomerLoginServlet extends CustomerServlet
{
	private static final long serialVersionUID = 1L;
	private final String className = "Customer Login Servlet: ";

	@Override
	//@requires HttpServletRequest !=NULL,  HttpServletResponse !=NULL ;
    //@assignable username,password;
    //@ensures password=db.GetPassword(), username=db.UserExists(username);
	//@signals_only RuntimeException, IOException,ServletException;
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException
	{
		ConnectDB();
		CustomerDB db = new CustomerDB();
		db.Setup(connection); 
				
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		
		try //check username and psw entered by the user, if they match the ones in database then login successful. Otherwise login failed message will be displayed
		{
			ReservationHelper.Setup(connection, username);
			ReservationHelper.UpdateResStatus(username);
			
			if (db.UserExists(username))
			{
				if (password.equals(db.GetPassword()))
				{
					String firstname = db.GetFirstName();
					String lastname = db.GetLastName();
					int point = db.GetLoyaltyPoint();
					String msg = null;
					int numRes = ReservationHelper.GetReservationList().size();
					int numPointToClaim = ReservationHelper.GetNumPointsToClaim();
					
					req.setAttribute("username", username);
					req.setAttribute("firstname", firstname);
					req.setAttribute("lastname", lastname);
					req.setAttribute("point", point);
					req.setAttribute("msg", msg);
					req.setAttribute("numRes", numRes);
					req.setAttribute("numPointToClaim", numPointToClaim);
									
					req.getRequestDispatcher("index_loggedin.jsp").forward(req, resp);
					System.out.println("log in success" + " " + username + " " + password);	
				}
				else
				{
					req.getRequestDispatcher("customer/login_failed_customer.jsp").forward(req, resp);
					System.out.println("log in failed. wrong password" + " " + username + " " + password);	
				}
			}
			else
			{
				req.getRequestDispatcher("customer/login_failed_customer.jsp").forward(req, resp);
				System.out.println("log in failed. user does not exist" + " " + username + " " + password);	//print out the login failed message 
			}
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
				
		
	}

}

